// utils/api.js
// const BASE_URL = ''; // 根据实际情况配置基础URL
const BASE_URL = 'https://api.example.com'; // TODO: 替换为你的后端接口域名，如有需要
const USE_MOCK = true; // 是否使用模拟数据，开发时可以设置为true

// 引入模拟数据
let mockAPI = null;
if (USE_MOCK) {
  try {
    const mockData = require('./mockData.js');
    mockAPI = mockData.mockAPI;
    mockAPI.mockLawyers = mockData.mockLawyers;
  } catch (error) {
    console.warn('模拟数据加载失败:', error);
  }
}

/**
 * 封装网络请求
 * @param {Object} options 请求配置
 */
function request(options) {
  return new Promise((resolve, reject) => {
    const token = wx.getStorageSync('token');
    
    wx.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'content-type': 'application/json',
        'Authorization': token || '',
        ...options.header
      },
      success: (res) => {
        if (res.statusCode === 200) {
          if (res.data.code === 200) {
            resolve(res.data);
          } else {
            // 业务错误
            reject(new Error(res.data.msg || '请求失败'));
          }
        } else {
          // HTTP错误
          reject(new Error(`HTTP错误: ${res.statusCode}`));
        }
      },
      fail: (err) => {
        console.error('网络请求失败:', err);
        reject(new Error('网络错误，请稍后再试'));
      }
    });
  });
}

/**
 * 收藏相关API
 */
const favoriteAPI = {
  // 添加收藏
  add: async (lawyerId) => {
    if (USE_MOCK && mockAPI) {
      return await mockAPI.addFavorite(lawyerId);
    }
    return request({
      url: '/app/favorite/add',
      method: 'POST',
      data: { lawyerId }
    });
  },

  // 取消收藏
  cancel: async (lawyerId) => {
    if (USE_MOCK && mockAPI) {
      return await mockAPI.cancelFavorite(lawyerId);
    }
    return request({
      url: '/app/favorite/cancel',
      method: 'POST',
      data: { lawyerId }
    });
  },

  // 获取收藏列表
  list: async (pageNum = 1, pageSize = 10) => {
    if (USE_MOCK && mockAPI) {
      return await mockAPI.getFavoriteList(pageNum, pageSize);
    }
    return request({
      url: '/app/favorite/list',
      method: 'GET',
      data: { pageNum, pageSize }
    });
  },

  // 检查收藏状态
  checkStatus: async (lawyerId) => {
    if (USE_MOCK && mockAPI) {
      return await mockAPI.checkFavoriteStatus(lawyerId);
    }
    return request({
      url: '/app/favorite/check',
      method: 'GET',
      data: { lawyerId }
    });
  }
};

/**
 * 用户相关API
 */
const userAPI = {
  // 微信登录
  wxLogin: (code, encryptedData, iv) => {
    return request({
      url: '/app/user/wxLogin',
      method: 'POST',
      data: { code, encryptedData, iv }
    });
  },

  // 账号登录
  login: (phoneNumber, password) => {
    return request({
      url: '/app/user/login',
      method: 'POST',
      data: { phoneNumber, password }
    });
  },

  // 注册
  register: (phoneNumber, password, nickName) => {
    return request({
      url: '/app/user/register',
      method: 'POST',
      data: { phoneNumber, password, nickName }
    });
  },

  // 绑定手机
  bindPhone: (phoneNumber, code) => {
    return request({
      url: '/app/user/bindPhone',
      method: 'POST',
      data: { phoneNumber, code }
    });
  }
};

/**
 * 律师相关API
 */
const lawyerAPI = {
  // 获取律师列表
  list: async (pageNum = 1, pageSize = 10, filters = {}) => {
    if (USE_MOCK && mockAPI) {
      let list = mockAPI.mockLawyers;
      // 多条件筛选
      if (filters) {
        if (filters.location && filters.location !== '全部') {
          list = list.filter(l => l.location && l.location.includes(filters.location));
        }
        if (filters.specialty && filters.specialty !== '全部') {
          list = list.filter(l => l.specialty && l.specialty.includes(filters.specialty));
        }
        if (filters.keyword) {
          list = list.filter(l => l.name.includes(filters.keyword) || l.lawFirm.includes(filters.keyword));
        }
        if (filters.onlineStatus !== undefined) {
          list = list.filter(l => l.onlineStatus === filters.onlineStatus);
        }
        if (filters.serviceType) {
          list = list.filter(l => l.serviceType && l.serviceType.includes(filters.serviceType));
        }
        if (filters.minPrice !== undefined) {
          list = list.filter(l => l.price !== undefined && l.price >= filters.minPrice);
        }
        if (filters.maxPrice !== undefined) {
          list = list.filter(l => l.price !== undefined && l.price <= filters.maxPrice);
        }
      }
      const start = (pageNum - 1) * pageSize;
      const end = start + pageSize;
      return Promise.resolve({
        code: 200,
        msg: 'success',
        data: {
          list: list.slice(start, end),
          total: list.length,
          pageNum,
          pageSize
        }
      });
    }
    return request({
      url: '/app/lawyer/list',
      method: 'GET',
      data: { pageNum, pageSize, ...filters }
    });
  },

  // 获取律师详情
  detail: async (lawyerId) => {
    if (USE_MOCK && mockAPI) {
      const lawyer = mockAPI.mockLawyers.find(l => l.lawyerId === lawyerId || l.id === lawyerId);
      return Promise.resolve({
        code: 200,
        msg: 'success',
        data: lawyer
      });
    }
    return request({
      url: `/app/lawyer/detail/${lawyerId}`,
      method: 'GET'
    });
  },

  // 推荐律师（评分优先）
  recommend: async (params = {}) => {
    if (USE_MOCK && mockAPI) {
      let list = [...mockAPI.mockLawyers];
      if (params.strategy === 'random') {
        // 随机排序
        list = list.sort(() => Math.random() - 0.5);
      } else {
        // 默认评分优先
        list.sort((a, b) => b.rating - a.rating);
      }
      return Promise.resolve({
        code: 200,
        msg: 'success',
        data: list
      });
    }
    return request({
      url: '/app/lawyer/recommend',
      method: 'GET',
      data: params
    });
  },

  search: async (params = {}) => {
    if (USE_MOCK && mockAPI) {
      let list = mockAPI.mockLawyers;
      if (params.keyword) {
        list = list.filter(l => l.name.includes(params.keyword) || l.lawFirm.includes(params.keyword) || (l.specialty && l.specialty.includes(params.keyword)));
      }
      return Promise.resolve({
        code: 200,
        msg: 'success',
        data: list
      });
    }
    return request({
      url: '/app/lawyer/search',
      method: 'GET',
      data: params
    });
  }
};

/**
 * 消息相关API
 */
const messageAPI = {
  // 获取消息列表
  list: async (params) => {
    if (USE_MOCK && mockAPI) {
      if (params.orderId) {
        // For chat detail page
        return await mockAPI.getChatHistory(params.orderId);
      } else {
        // For chat list page
        return await mockAPI.getMessageList(params.pageNum, params.pageSize);
      }
    }
    return request({
      url: '/app/message/list',
      method: 'GET',
      data: params
    });
  },

  // 发送消息
  send: async (orderId, content) => {
    if (USE_MOCK && mockAPI) {
      return await mockAPI.sendMessage({ orderId, content });
    }
    return request({
      url: '/app/message/send',
      method: 'POST',
      data: { orderId, content }
    });
  },

  // 标记消息为已读
  read: async (orderId) => {
    if (USE_MOCK && mockAPI) {
      return await mockAPI.readMessages(orderId);
    }
    return request({
      url: '/app/message/read',
      method: 'POST',
      data: { messageId: orderId } // As per API doc, it expects messageId. Assuming orderId can be used here for concept.
    });
  }
};

// 订单相关API
const createOrder = (data) => request('/app/order/create', data, 'POST');
const getOrderList = (params) => request('/app/order/list', params, 'GET');
const getOrderDetail = (orderId) => request(`/app/order/detail/${orderId}`, {}, 'GET');
const cancelOrder = (orderId) => request('/app/order/cancel', { orderId }, 'POST');
const payOrder = (orderId, paymentType) => request('/app/order/pay', { orderId, paymentType }, 'POST');
const completeOrder = (orderId) => request('/app/order/complete', { orderId }, 'POST');
const commentOrder = (orderId, content, rating) => request('/app/order/comment', { orderId, content, rating }, 'POST');

/**
 * 评论相关API
 */
const commentAPI = {
  // 获取评论列表
  list: async (lawyerId, sort) => {
    if (USE_MOCK && mockAPI) {
      return await mockAPI.getCommentList({ lawyerId, sort });
    }
    return request({
      url: '/app/comment/list',
      method: 'GET',
      data: { lawyerId, sort }
    });
  },

  // 发表评论
  add: async (orderId, content, rating) => {
    if (USE_MOCK && mockAPI) {
      // The old mock function `commentOrder` has the same functionality.
      return await mockAPI.commentOrder({ orderId, content, rating });
    }
    return request({
      url: '/app/comment/add',
      method: 'POST',
      data: { orderId, content, rating }
    });
  },

  // 回复评论
  reply: async (commentId, content) => {
    if (USE_MOCK && mockAPI) {
      return await mockAPI.replyToComment({ commentId, content });
    }
    return request({
      url: '/app/comment/reply',
      method: 'POST',
      data: { commentId, content }
    });
  }
};

module.exports = {
  request,
  favoriteAPI,
  userAPI,
  lawyerAPI,
  messageAPI,
  USE_MOCK,
  createOrder,
  getOrderList,
  getOrderDetail,
  cancelOrder,
  payOrder,
  completeOrder,
  commentOrder,
  commentAPI
}; 